#!/usr/bin/python3
# -*- coding: utf-8 -*-


import requests,requests_cache
from prettyprinter import cpprint
from prettytable import PrettyTable
import click
from prompt_toolkit import prompt
from config import *
from datetime import datetime

requests_cache.install_cache('BTMExplorer', backend='sqlite', expire_after=10)

print(LOGO)
print('A CLI Bytom Explore For Developer')

state_table = PrettyTable(['日期','出块数量','新增地址数','新增资产数','总交易量数','当前算力'])
miner_table = PrettyTable(['矿池','算力分布'])

# 进度条
with click.progressbar([1])as bar:
    for x in bar:
        dailyData = requests.get(DailyAPI,headers=RequestHeaders,timeout=TIMEOUT).json()
        hashData = requests.get(HashrateAPI,headers=RequestHeaders,timeout=TIMEOUT).json()
        minerData = requests.get(MinerAPI,headers=RequestHeaders,timeout=TIMEOUT).json()

state_table.add_row(
    [dailyData[0]['date'],
     dailyData[0]['mainnet_block_count'],
     dailyData[0]['new_address_count'],
     dailyData[0]['new_asset_count'],
     dailyData[0]['transaction_count'],
     str(hashData[-1][1]/1000000)+'MH/s']
)

print(state_table)

# Miners
for y in minerData:
    no = float(y['percent'].replace('%',''))
    no = int(no)
    no = int(no/2)
    percentblock = no * BLOCK
    percent = y['percent']
    miner_table.add_row(['{miner}'.format(miner=y['name']),'{block}  {percent}'.format(block=percentblock,percent=percent)])

print(miner_table)

# Search by Address
def saddress(addr):
    addrData = requests.get(AddressAPI.format(address=addr,headers=RequestHeaders,count=100,page=1)).json()
    if addrData.get('address'):
        result = {
            'address':addrData['address'],
            'balance':addrData['balance']/100000000,
            'receive':addrData['receive']/100000000,
            'sent':addrData['sent']/100000000,
            'transaction_count':addrData['transaction_count'],
            'detail':addrData['transactions']
        }
    else:
        result = {
            'status': -1,
            'errmsg': 'You should input valid Bytom address'
        }
    return result

# Search by Tx
def stx(txid):
    txData = requests.get(TransactionAPI.format(tx=txid),headers=RequestHeaders,timeout=TIMEOUT).json()
    if txData.get('id'):
        result = {
            'txid':txData['id'],
            'amount':txData['transaction_amount']/100000000,
            'confirmations':txData['confirmations'],
            'time':datetime.fromtimestamp(txData['timestamp']),
            'blockNo':txData['height'],
            'detail':txData['detail']
        }
    else:
        result = {
            'status': -1,
            'errmsg':'You should input valid Txid'
        }
    return result

print(Help)
# 进入REPL交互式界面，提供地址和交易id查询功能
while True:
    start = prompt('BTMMAN>')
    if start == 'help':
        print(Help)
    if start[:2] == 'tx':
        txid = start.split(' ')[1]
        result = stx(txid)
        cpprint(result)
    if start[:4] == 'addr':
        addr = start.split(' ')[1]
        result = saddress(addr)
        cpprint(result)
    if start == 'clear':
        click.clear()
    if start == 'exit':
        print('Exiting ... Bye ~ ')
        break







